package xin.ryven.car.android.utils

import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.ConnectException
import java.util.concurrent.TimeUnit

object NetworkTestUtils {
    
    private const val TAG = "NetworkTest"
    
    suspend fun testConnection(context: Context): Boolean {
        return withContext(Dispatchers.IO) {
            try {
                val client = OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .build()

                val baseUrl = "http://192.168.1.7:8666/"
                
                val request = Request.Builder()
                    .url(baseUrl)
                    .build()

                val response = client.newCall(request).execute()
                val success = response.isSuccessful
                
                Log.d(TAG, "Connection test to $baseUrl: ${if (success) "SUCCESS" else "FAILED"}")
                Log.d(TAG, "Response code: ${response.code}")
                
                response.close()
                success
                
            } catch (e: ConnectException) {
                Log.e(TAG, "Connection failed: ${e.message}")
                false
            } catch (e: Exception) {
                Log.e(TAG, "Network test error: ${e.message}")
                false
            }
        }
    }
    
    private fun isEmulator(): Boolean {
        return (android.os.Build.FINGERPRINT.startsWith("generic")
                || android.os.Build.FINGERPRINT.startsWith("unknown")
                || android.os.Build.MODEL.contains("google_sdk")
                || android.os.Build.MODEL.contains("Emulator")
                || android.os.Build.MODEL.contains("Android SDK built for x86")
                || android.os.Build.MANUFACTURER.contains("Genymotion")
                || (android.os.Build.BRAND.startsWith("generic") && android.os.Build.DEVICE.startsWith("generic"))
                || "google_sdk" == android.os.Build.PRODUCT)
    }
} 